package com.xxxcoampany.servlet;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebFilter("/*")
public class LoginFilter implements Filter{
	
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		
		// 如果没有登陆，不让访问 main.jsp 和 B.jsp
		
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		HttpSession session = req.getSession();
		String username = (String)session.getAttribute("username");
		
		if(username!=null)
		{
			System.out.println("已登录放行");
			chain.doFilter(request, response);
			return;
		}
		else
		{
			System.out.println("如果没有登陆");
			// 得判断当前请求的是不是登陆相关的页面
			
			// 访问页面的路径
			String req_url = req.getRequestURI();// /11-%E8%BF%87%E6%BB%A4%E5%99%A8Filter/login.jsp
			System.out.println(req_url);
			// 应用的路径
			String app_url = req.getContextPath(); // /11-%E8%BF%87%E6%BB%A4%E5%99%A8Filter/
			System.out.println(app_url);
			// 获得用户访问的页面	
			String page_url = req_url.substring(app_url.length());
			System.out.println("当前访问的页面是:"+page_url); // login.jsp
			
			
			if("/login.jsp".equals(page_url)
					||"/login.jsp".equals(page_url)
					||"/logout".equals(page_url))
			{
				// 放行
				System.out.println("是登陆相关页面，放行");
				chain.doFilter(request, response);	
			}
			else
			{
				// 跳转登录页
				System.out.println("未登录，跳转登录页");
				resp.sendRedirect("login.jsp");
			}
			
		}
		
	}

}